import { useCascaderAreaData } from "./area-data";
import { ref, watch, onMounted } from "vue";
import apis from "../../api/index";
const { selectUniversityDetail, selectCommonConfigDetail } = apis;
export interface formItem {
  key?: string | string[];
  label: string;
  value: any;
  component: string;
  tip?: string;
  format?: string;
  options?: any;
  max?: number;
  min?: number;
  minDate?: Date;
  maxDate?: Date;
  preTip?: string;
  isNotVal?: boolean;
  id?: string;
  loading?: boolean;
  text?: string;
  sign?: string;
  parentLabel?: string;
  show?: boolean;
  delWith?: string;
  count?: number;
  bold?: boolean;
  index?: number;
  mainTitle?: boolean;
  divide?: boolean;
  useElement?: boolean;
  inputVal?: string;
  withInput?: boolean;
  reflectLabel?: string;
  tips?: string[];
  picsrc?: string;
  showError?: boolean;
  showErrorMsg?: string;
  maxlength?: number;
  useHttpOptions?: string;
  notRequire?: boolean;
}
export interface Modules {
  label: string;
  list: formItem[];
  desc?: string;
  skew?: boolean;
}
interface Options {
  label: string;
  value: string | number;
}
const educationCount = ref<number>(0);
const competitionCount = ref<number>(0);
const familyCount = ref<number>(0);
const practiceCount = ref<number>(0);

export const getCommonConfigDetail = async (
  key: string
): Promise<Options[]> => {
  const data: any = await selectCommonConfigDetail({ type: key });
  let list: Options[] = [];
  list = data.data.map((el) => {
    return {
      label: el.label,
      value: el.label,
    };
  });
  return list;
};

const educationList = ref<formItem[][]>([
  [
    {
      key: "qualificationType",
      value: "硕士",
      label: "",
      component: "",
      delWith: "education-master",
    },
    {
      preTip: "教育经历-硕士",
      options: [],
      value: "",
      label: "学校名称",
      key: "schoolName",
      component: "remote",
      delWith: "education-master",
      tip: "请输入学校全称，国内院校请输入中文名，如：哈尔滨工业大学（深圳）；海外院校请输入英文名，如：Columbia University",
    },
    {
      value: ["", ""],
      label: "起止时间",
      component: "dateRange",
      delWith: "education-master",
      format: "YYYY-MM",
      key: ["educationalStartTime", "educationalEndTime"],
    },
    {
      value: "",
      label: "院系",
      component: "input",
      key: "schoolDepartment",
      delWith: "education-master",
    },
    {
      value: "",
      label: "专业",
      component: "input",
      key: "specialty",
      delWith: "education-master",
    },
  ],

  [
    {
      key: "qualificationType",
      value: "博士",
      label: "",
      component: "",
      delWith: "education-doctor",
    },
    {
      preTip: "教育经历-博士",
      options: [],
      value: "",
      label: "学校名称",
      key: "schoolName",
      delWith: "education-doctor",
      component: "remote",
      tip: "请输入学校全称，国内院校请输入中文名，如：哈尔滨工业大学（深圳）；海外院校请输入英文名，如：Columbia University",
    },
    {
      value: ["", ""],
      label: "起止时间",
      component: "dateRange",
      delWith: "education-doctor",
      format: "YYYY-MM",
      key: ["educationalStartTime", "educationalEndTime"],
    },
    {
      value: "",
      label: "院系",
      component: "input",
      key: "schoolDepartment",
      delWith: "education-doctor",
    },
    {
      value: "",
      label: "专业",
      component: "input",
      key: "specialty",
      delWith: "education-doctor",
    },
  ],
]);

const competitionList = ref<formItem[]>([
  {
    preTip: "奖项",
    show: true,
    value: "",
    label: "竞赛类别",
    component: "select",
    delWith: "competition",
    index: 1,
    key: "competitionType",
    options: [],
    useHttpOptions: "COMPETITION",
  },
  {
    value: "",
    show: true,
    label: "等级/奖项",
    component: "textarea",
    delWith: "competition",
    key: "competitionLevel",
  },
]);

const practiceList = ref<formItem[]>([
  {
    preTip: "实习经历",
    show: true,
    value: "",
    label: "公司名称",
    component: "input",
    delWith: "pratice",
    index: 1,
    key: "workPlace",
  },
  {
    value: "",
    show: true,
    label: "岗位",
    component: "input",
    delWith: "pratice",
    key: "workPost",
  },
  {
    value: ["", ""],
    show: true,
    label: "起止时间",
    component: "dateRange",
    delWith: "pratice",
    key: ["workStartDate", "workEndDate"],
  },
  {
    value: "",
    show: true,
    label: "工作（实习）/培训内容",
    component: "textarea",
    delWith: "pratice",
    key: "workDetail",
    notRequire: true,
  },
]);

const familyList = ref<formItem[]>([
  {
    preTip: "家庭成员",
    key: "relation",
    show: true,
    index: 1,
    value: "",
    label: "关系",
    component: "input",
    delWith: "family",
  },
  {
    show: true,
    value: "",
    label: "姓名",
    component: "input",
    delWith: "family",
    key: "name",
  },
  {
    show: true,
    key: "age",
    value: "",
    label: "年龄",
    component: "input",
    delWith: "family",
  },
  {
    show: true,
    value: "",
    key: "phone",
    label: "联系电话",
    component: "input",
    delWith: "family",
  },
  {
    key: "workPlace",
    show: true,
    value: "",
    label: "工作单位",
    component: "input",
    delWith: "family",
  },
  {
    show: true,
    key: "occupation",
    value: "",
    label: "职务",
    component: "input",
    delWith: "family",
  },
]);

export const formList = ref<Modules[]>([
  {
    label: "基础信息",
    list: [
      {
        label: "个人照片",
        value: [],
        component: "upload",
        notRequire: true,
      },
      {
        label: "姓名",
        value: "",
        component: "input",
        key: "userName",
        showErrorMsg: "请填写真实姓名",
      },
      {
        label: "性别",
        key: "sex",
        value: "",
        component: "radio",
        options: [
          { label: "男", value: "0" },
          { label: "女", value: "1" },
        ],
      },
     /* {
        key: "certificateType",
        label: "证件类型",
        value: "",
        component: "select",
        options: [],
        useHttpOptions: "CERTIFICATE",
        tip: `1、中国大陆籍请填写身份证信息，该信息作为身份识别的重要依据。 
          2、每人仅允许填写一次个人证件类型及证件号码。简历提交成功后无法自助修改。
          如确有修改需求，请将修改原因，新旧证件具体信息等证明材料发送到ftzhaopin@fangtian.me邮箱说明。 
          3、每人仅允许注册和使用一份简历应聘，在个人简历信息注册完成后，
          使用本人其他类型证件（如护照、港澳永久身份证、台胞证等）注册新简历的行为、
          或通过修改及编纂身份证号以新增注册简历的行为，将被视为重复注册和使用简历应聘。
          重复注册简历应聘的行为一经发现将取消当前面试和录用资格。 
          4、若出现证件信息被占用的情况，请发邮件到ftzhaopin@fangtian.me邮箱说明。
          `,
        showErrorMsg: "请选择证件类型",
      },
      {
        key: "certificateNumber",
        label: "证件号码",
        value: "",
        component: "input",
        showErrorMsg: "请填写您的证件号码",
      },*/
      // {
      //   value: '',
      //   label: '手机号码',
      //   key: 'phoneNumer',
      //   component: 'input',
      //   maxlength: 11,
      // },
      {
        label: "电子邮箱",
        key: "email",
        value: "",
        component: "input",
        showErrorMsg: "请输入您的常用邮箱地址",
      },
      {
        key: "birthday",
        label: "出生年月",
        value: "",
        component: "datePicker",
        format: "YYYY-MM-DD",
        minDate: new Date(1980, 1, 1),
        maxDate: new Date(),
        showErrorMsg: "请选择出生年月",
      },
      {
        label: "籍贯",
        key: "birthplace",
        value: "",
        component: "cascader",
        options: useCascaderAreaData(),
        showErrorMsg: "请选择籍贯",
      },
    ],
  },
  {
    label: "投递岗位",
    desc: "此处仅做初步了解，不代表分配的最终结果，培训期间会再次确认。",
    list: [
      {
        key: "intentionPostList",
        label: "应聘岗位科目（最多选三项）",
        bold: true,
        value: [],
        component: "checkbox",
        max: 3,
        useHttpOptions: "POST_SUBJECT",
        options: [],
      },
      {
        key: "intentionGrade",
        value: [],
        label: "意向年级段（最多选两项）",
        bold: true,
        component: "checkbox",
        max: 2,
        useHttpOptions: "INTENTION_GRADE",
        options: [],
      },
      {
        key: "intentionSubject",
        value: [],
        label: "意向学科（最多选三项）",
        bold: true,
        component: "checkbox",
        max: 3,
        useHttpOptions: "INTENTION_SUBJECT",
        options: [],
      },

      {
        key: "intentionPlace",
        value: [],
        label: "意向工作地点（最多选三项）",
        bold: true,
        component: "checkbox",
        max: 3,
        options: [],
        useHttpOptions: "INTENTION_PlACE",
      },
     /* {
        key: "intentionDate",
        value: "",
        label: "最早可入职时间",
        component: "datePicker",
        minDate: new Date(),
        format: "YYYY-MM-DD",
        maxDate: new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365),
        showErrorMsg: "请选择日期",
      },*/
    ],
  },
  {
    label: "教育经历",
    list: [
      {
        key: "qualificationType",
        value: "高中",
        label: "",
        component: "",
        delWith: "education-shc",
      },
      {
        preTip: "教育经历-高中",
        value: "",
        label: "学校名称",
        key: "schoolName",
        delWith: "education-shc",
        component: "input",
        tip: "请输入学校全称，国内院校请输入中文名，如：哈尔滨工业大学（深圳）；海外院校请输入英文名，如：Columbia University",
      },
      {
        value: ["", ""],
        label: "起止时间",
        delWith: "education-shc",
        component: "dateRange",
        format: "YYYY-MM",
        key: ["educationalStartTime", "educationalEndTime"],
      },
      {
        key: "qualificationType",
        value: "本科",
        label: "",
        delWith: "education-uc",
        component: "",
      },
      {
        preTip: "教育经历-本科",
        delWith: "education-uc",
        options: [],
        value: "",
        label: "学校名称",
        key: "schoolName",
        component: "remote",
        loading: false,
        tip: "请输入学校全称，国内院校请输入中文名，如：哈尔滨工业大学（深圳）；海外院校请输入英文名，如：Columbia University",
      },
      {
        value: ["", ""],
        label: "起止时间",
        delWith: "education-uc",
        component: "dateRange",
        key: ["educationalStartTime", "educationalEndTime"],
        format: "YYYY-MM",
      },
      {
        value: "",
        label: "院系",
        component: "input",
        delWith: "education-uc",
        key: "schoolDepartment",
      },
      {
        value: "",
        label: "专业",
        delWith: "education-uc",
        component: "input",
        key: "specialty",
      },
      {
        value: "",
        label: "",
        text: "添加",
        component: "add",
        isNotVal: true,
        sign: "education",
      },
    ],
  },
  {
    label: "工作（实习）/培训经历",
    list: [
      {
        value: "",
        label: "",
        component: "del",
        isNotVal: true,
        delWith: "pratice",
        text: "删除",
        count: -1,
      },
      ...JSON.parse(JSON.stringify(practiceList.value)),
      {
        value: "",
        label: "",
        text: "添加",
        component: "add",
        isNotVal: true,
        sign: "pratice",
      },
    ],
  },
  {
    label: "竞赛获奖经历",
    list: [
      {
        value: "",
        label: "",
        component: "del",
        isNotVal: true,
        delWith: "competition",
        text: "删除",
        count: -1,
      },
      ...JSON.parse(JSON.stringify(competitionList.value)),
      {
        value: "",
        label: "",
        text: "添加",
        component: "add",
        isNotVal: true,
        sign: "competition",
      },
    ],
  },
  {
    label: "语言能力",
    skew: true,
    list: [
      {
        value: "",
        label: "",
        text: "删除",
        component: "del",
        delWith: "langs",
        show: false,
        isNotVal: true,
      },
      {
        show: false,
        value: [undefined, ""],
        label: "外语考试/等级",
        component: "assembly",
        key: ["foreignLanguagesGrade", "foreignLanguagesScore"],
        delWith: "langs",
        options: [],
        useHttpOptions: "LANGUAGES",
      },
      {
        value: "",
        label: "",
        delWith: "langs",
        component: "add",
        text: "添加",
        show: true,
        isNotVal: true,
        sign: "langs",
      },
    ],
  },
  // {
  //   label: "家庭情况",
  //   list: [
  //     {
  //       value: "",
  //       type: "",
  //       label: "",
  //       component: "del",
  //       delWith: "family",
  //       text: "删除",
  //       show: true,
  //       isNotVal: true,
  //       count: -1,
  //     },
  //     ...familyList.value,
  //     {
  //       value: "",
  //       label: "",
  //       text: "添加",
  //       component: "add",
  //       isNotVal: true,
  //       sign: "family",
  //     },
  //   ],
  // },
  {
    label: "择业倾向",
    desc: "（按重要程度依次选择，最多选3项）",
    skew: true,
    require: true,
    list: [
      {
        value: [],
        label: "",
        key: "standards",
        mainTitle: true,
        component: "checkbox",
        useElement: true,
        max: 3,
        divide: true,
        useHttpOptions: "EMPLOYMENT_STANDARDS",
        options: [],
      },
    ],
  },
  {
    label: "应聘信息来源",
    skew: true,
    require: true,
    list: [
      {
        value: "",
        label: "",
        mainTitle: true,
        component: "radio",
        key: "source",
        divide: true,
        useHttpOptions: "INFORMATION_SOURCE",
        options: [],
        withInput: true,
        inputVal: "",
        reflectLabel: "其他",
      },
    ],
  },
  {
    label:'最早可入职时间',
    list: [
       {
      key: "intentionDate",
      value: "",
      label: "最早可入职时间",
      component: "datePicker",
      minDate: new Date(),
      format: "YYYY-MM-DD",
      maxDate: new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365),
      showErrorMsg: "请选择日期",
    },
    ]
  },
  {
    label: "是否内推",
    list: [
      {
        value: "",
        type: "",
        show: true,
        key: "isRecommends",
        label: "是否内推",
        rules: [{ required: true }],
        component: "radio",
        direction: "horizontal",
        options: [
          { label: "是", value: "0" },
          { label: "否", value: "1" },
        ],
      },
      {
        value: "",
        type: "",
        label: "内推人",
        key: "recommendsName",
        show: true,
        rules: [
          {
            required: true,
          },
        ],
        component: "input",
      },
      {
        value: "",
        type: "",
        show: true,
        label: "内推人手机号",
        key: "recommendsPhone",
        rules: [
          {
            required: true,
            pattern:
              /^1(3[0-9]|4[5-9]|5[0-35-9]|6[5-6]|7[0-8]|8[0-9]|9[1-35-9])\d{8}$/,
          },
        ],
        component: "input",
        maxlength: 11,
      },
    ],
  },
  {
    label: "简历附件",
    skew: true,
    list: [
      {
        value: [],
        mainTitle: true,
        label: "",
        component: "uploadarea",
        notRequire: true,
        tips: ["请将文件大小控制在2M以内。", "附件仅支持word和pdf文档。"],
      },
    ],
  },
]);
export const getOptions = (v: formItem) => {
  if (!v.useHttpOptions) return;
  const id = v.id;
  formList.value.forEach((el: Modules) => {
    el.list.forEach(async (item: formItem) => {
      if (item.id === id) {
        v.options = await getCommonConfigDetail(item.useHttpOptions);
      }
    });
  });
};
watch(
  () => formList.value,
  (val: Modules[]) => {
    val.forEach((el, idx) => {
      el.list.forEach((v: formItem) => {
        v.parentLabel = el.label;
        if (v.show !== false) {
          v.show = true;
        }
        if (v.sign == "education") {
          v.show = !(educationCount.value == 2);
        } else if (v.sign == "pratice") {
          v.show = !(practiceCount.value == 3);
        } else if (v.sign == "competition") {
          v.show = !(competitionCount.value == 3);
        } else if (v.sign == "family") {
          v.show = !(familyCount.value == 4);
        }
      });
      el.list.forEach((a: formItem, index) => {
        a.id = `${idx + 1}-${index + 1}`;
        if (a.useHttpOptions && a?.options?.length == 0) {
          a.options = getOptions(a);
        }
      });
    });
  },
  { immediate: true, deep: true }
);

watch(
  () => formList.value[9].list,
  (val) => {
    //选择否
    val[1].show = val[2].show = val[0].value !== "1";
  },
  {
    deep: true,
  }
);

export const getShcool = (val: string, v: formItem) => {
  const id = v.id;
  formList.value.forEach((el: Modules) => {
    el.list.forEach(async (item: formItem) => {
      if (item.id === id) {
        v.options = await getUniversityDetail(val);
      }
    });
  });
};
const getUniversityDetail = async (schoolName: string) => {
  console.log(schoolName, "val");
  if (schoolName === "") {
    // return [];
    schoolName = "北京";
  }
  const data: any = await selectUniversityDetail({ schoolName: schoolName });
  if (data && data.code === "10000") {
    const list = data.data.map((el) => {
      return {
        label: el.universityName,
        value: el.universityName,
      };
    });
    return list;
  } else {
    return [];
  }
};

export const append = (item: formItem) => {
  let current = formList.value.find(
    (e) => e.label === item.parentLabel
  ) as Modules;
  const delMap = {
    value: "",
    label: "",
    component: "del",
    isNotVal: true,
    delWith: "",
    text: "删除",
    count: -1,
  };
  let random = Math.random();
  if (item.sign === "education") {
    delMap.count = educationCount.value;
    let delWith = "education" + "-" + random;
    delMap.delWith = delWith;
    appendEdu(current, delWith, delMap);
  } else if (item.sign === "pratice") {
    let delWith = "pratice" + "-" + random;
    delMap.delWith = delWith;
    delMap.count = practiceCount.value;
    appendPratice(current, delWith, delMap);
  } else if (item.sign === "competition") {
    let delWith = "competition" + "-" + random;
    delMap.delWith = delWith;
    delMap.count = competitionCount.value;
    appendCompetition(current, delWith, delMap);
  } else if (item.sign === "langs") {
    current.list.forEach((el) => {
      el.show = !(el.component == "add");
    });
  } else if (item.sign === "family") {
    let delWith = "family" + "-" + random;
    delMap.delWith = delWith;
    delMap.count = familyCount.value;
    appendFamily(current, delWith, delMap);
  }
};

const appendEdu = (current: Modules, delWith: string, delMap: formItem) => {
  let list = educationList.value[educationCount.value];
  current.list.forEach((v) => {
    if (v.count == educationCount.value - 1) {
      v.show = false;
    }
  });
  list.forEach((el) => {
    el.delWith = delWith;
  });
  const val: formItem[] = [delMap, ...list];
  current?.list.splice(current?.list.length - 1, 0, ...val);
  educationCount.value++;
};

const appendPratice = (current: Modules, delWith: string, delMap: formItem) => {
  let list = JSON.parse(JSON.stringify(practiceList.value));
  current.list.forEach((v) => {
    if (v.count == practiceCount.value - 1) {
      v.show = false;
    }
  });
  list.forEach((el: formItem) => {
    el.delWith = delWith;
    if (el.component === "dateRange") {
      el.minDate = new Date(1980, 1, 1);
      el.maxDate = new Date();
    }
  });
  list[0].index = Number(delMap.count) + 2;
  const val: formItem[] = [delMap, ...list];
  current?.list.splice(current?.list.length - 1, 0, ...val);
  practiceCount.value++;
};

const appendCompetition = (
  current: Modules,
  delWith: string,
  delMap: formItem
) => {
  let list = JSON.parse(JSON.stringify(competitionList.value));
  current.list.forEach((v) => {
    if (v.count == competitionCount.value - 1) {
      v.show = false;
    }
  });
  list.forEach((el: formItem) => {
    el.delWith = delWith;
  });
  list[0].index = Number(delMap.count) + 2;
  const val: formItem[] = [delMap, ...list];
  current?.list.splice(current?.list.length - 1, 0, ...val);
  competitionCount.value++;
};

const appendFamily = (current: Modules, delWith: string, delMap: formItem) => {
  let list = JSON.parse(JSON.stringify(familyList.value));
  current.list.forEach((v) => {
    if (v.count == familyCount.value - 1) {
      v.show = false;
    }
  });
  list.forEach((el: formItem) => {
    el.delWith = delWith;
    el.value = "";
  });
  list[0].index = Number(delMap.count) + 2;
  const val: formItem[] = [delMap, ...list];
  current?.list.splice(current?.list.length - 1, 0, ...val);
  familyCount.value++;
};

export const del = (item: formItem) => {
  let current = formList.value.find(
    (e) => e.label === item.parentLabel
  ) as Modules;
  let sign = item.delWith?.split("-")[0];
  if (sign === "education") {
    delEdu(current, item);
  } else if (sign == "pratice") {
    delPratice(current, item);
  } else if (sign == "competition") {
    delCompetition(current, item);
  } else if (sign == "langs") {
    current.list.forEach((el) => {
      el.show = el.component == "add";
    });
  } else if (sign == "family") {
    delFamily(current, item);
  }
};

const delEdu = (current: Modules, item: formItem) => {
  educationCount.value--;
  current.list = current.list.filter((e) => e.delWith !== item.delWith);
  current.list.forEach((v) => {
    if (v.count == educationCount.value - 1) {
      v.show = true;
    }
  });
};

const delPratice = (current: Modules, item: formItem) => {
  practiceCount.value--;
  current.list = current.list.filter((e) => e.delWith !== item.delWith);
  current.list.forEach((v) => {
    if (v.count == practiceCount.value - 1) {
      v.show = true;
    }
  });
};

const delCompetition = (current: Modules, item: formItem) => {
  competitionCount.value--;
  current.list = current.list.filter((e) => e.delWith !== item.delWith);
  current.list.forEach((v) => {
    if (v.count == competitionCount.value - 1) {
      v.show = true;
    }
  });
};

const delFamily = (current: Modules, item: formItem) => {
  familyCount.value--;
  current.list = current.list.filter((e) => e.delWith !== item.delWith);
  current.list.forEach((v) => {
    if (v.count == familyCount.value - 1) {
      v.show = true;
    }
  });
};
